#include "widget.h"
#include "ui_widget.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("斗地主");
    initUi();
    initConnections();
}

void Widget::initUi()
{
    QVBoxLayout *layout = new QVBoxLayout(this);
    QHBoxLayout *layoutAddress = new QHBoxLayout;
    QHBoxLayout *layoutPort = new QHBoxLayout;

    inputAddress = new QLineEdit;
    inputPort = new QLineEdit;

    labelAddress = new QLabel;
    labelAddress->setText("server address:");
    labelAddress->setAlignment(Qt::AlignLeft);

    labelPort = new QLabel;
    labelPort->setText("server port:");
    labelPort->setAlignment(Qt::AlignLeft);

    btnEnableServer = new QRadioButton;
    btnEnableServer->setText("start server");

    btnConnect = new QPushButton;
    btnConnect->setText("开始连接");

    layoutAddress->addWidget(labelAddress);
    layoutAddress->addWidget(inputAddress);
    layoutPort->addWidget(labelPort);
    layoutPort->addWidget(inputPort);

    layout->addLayout(layoutAddress);
    layout->addLayout(layoutPort);
    layout->addWidget(btnEnableServer);
    layout->addWidget(btnConnect);
}

void Widget::initConnections()
{
    connect(btnConnect, &QPushButton::clicked, this, &Widget::startConnection);
}

void Widget::startConnection()
{
    enableWidgets(false);

    QHostAddress address(inputAddress->text());
    quint16 port = static_cast<quint16>(inputPort->text().toInt());

    if (btnEnableServer->isChecked()) {
        emit launchServer(port);
    }
    emit launchClient(address, port);
}

void Widget::enableWidgets(bool value)
{
    inputAddress->setEnabled(value);
    inputPort->setEnabled(value);
    btnEnableServer->setEnabled(value);
    btnConnect->setEnabled(value);
}

Widget::~Widget()
{
    delete ui;
}
